題目連結(https://leetcode.com/problems/teemo-attacking/description/)
Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly duration
seconds. More formally, an attack at second t
will mean Ashe is poisoned during the inclusive time interval [t, t + duration - 1]
. If Teemo attacks again before the poison effect ends, the timer for it is reset, and the poison effect will end duration
seconds after the new attack.
You are given a non-decreasing integer array timeSeries
, where timeSeries[i]
denotes that Teemo attacks Ashe at second timeSeries[i]
, and an integer duration
.
Return the total number of seconds that Ashe is poisoned.
每日一題是water bottle2 改挑一題 easy 分享
timeSeries
, 整數 duration
1 <= timeSeries.length <= 104
0 <= timeSeries[i], duration <= 107
timeSeries
is sorted in non-decreasing order.Input: timeSeries = [1,4], duration = 2
Output: 4
Explanation: Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5.
Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.
時間軸: 0 1 2 3 4 5 6
攻擊: ↓ ↓
中毒: [--] [--]
結果: 1,2,4,5 = 4秒
class Solution {
public:
int findPoisonedDuration(vector<int>& timeSeries, int duration) {
int result = 0;
int gap = 0;
for(int i = 0; i < timeSeries.size()-1; i++){
gap = timeSeries[i+1] - timeSeries[i];
result += min(duration, gap);
}
result += duration; //LAST ATTACK
return result;
}
};
timeSeries = [1, 2, 3, 4, 5]
duration = 5
result = sol.findPoisonedDuration(timeSeries, duration)
print(f"Example: {result}")
# Expected: 9
print(f"說明: 連續攻擊不斷重置,最後一次攻擊完整5秒")
print(f"實際: 1+1+1+1+5 = 9秒\n")
用 min(duration, gap) 控制,不用再額外寫判斷式就能處理兩種情況
for(int i = 0; i < timeSeries.size()-1; i++){
gap = timeSeries[i+1] - timeSeries[i];
result += min(duration, gap);
}
ps. 部分內容經 AI 協助整理